package com.hyopt.modules.app.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.codec.Base64;
import com.hyopt.common.utils.MD5Util;
import com.hyopt.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @ClassName 羚羊免密登陆
 * @Description 羚羊免密登陆
 * @Author lijie
 * @Date 2023年3月10日15:52:03
 * @Version 1.0
 */
@Component
@Service
@Slf4j
public class LingYang {

    @Autowired
    private RedisUtils redisUtils;

    public static final String AppKey = "tztnykwxup";

    public static final String AppSecret = "033c2663286336cfc77db41721a8ef7f2579dc1f";

    public static final String AESKey = "hvxtjqcroeebplqy";

    public static void main(String[] args) throws Exception {
        // 获取签名
        String body = "{\"token\":\"1676276575000001-OPEN-b0bdf3a33cb24c81b39962f44286df71\"}";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf.format(new Date());
        String unSignStr = AppSecret +"_" + body + "_" + time + "_" + AppKey +"_" +AppSecret;
        log.info("未加签:{}" , unSignStr);
        String signStr = MD5Util.MD5(unSignStr).toUpperCase(Locale.ROOT);
        log.info("已加签:{}" ,  signStr);
        String url = "https://www.lingyangplat.com/antelope-other/open/v1/user/getUserInfo";

        // 请求并返回对话结果
        HttpRequest request = HttpUtil.createPost(url);
        request.header("Content-Type", "application/json");
        request.header("channel", "app02");
        request.header("time",System.currentTimeMillis() + "");
        request.header("appKey",AppKey);
        request.header("sign",signStr);
        request.setReadTimeout(20000);
        cn.hutool.json.JSONObject param = JSONUtil.createObj();
        request.body(aesEncrypt("{\"token\":\"1676276575000001-OPEN-b0bdf3a33cb24c81b39962f44286df71\"}",AESKey,"UTF-8"));
        HttpResponse response = request.execute();
        String res = response.body();
        if (response.getStatus() == 200) {
            System.out.println(res);
            System.out.println("解密回包" + aesDecrypt(res,AESKey,"UTF-8"));
//            responseJson = JSONObject.parseObject(res);
//            System.out.println(responseJson);
        }else {
            log.info("调用结果{}",res);
        }

    }


    /**
     * AES解密
     *
     * @param content
     * @param key
     * @param charset
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String content, String key, String charset)
            throws Exception {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            String str = "0000000000000000";
            IvParameterSpec iv = new IvParameterSpec(str.getBytes()); //0000000000000000.getBytes()
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"), iv);
            byte[] cleanBytes = cipher.doFinal(Base64.decodeBase64(content.getBytes(Charset.forName("utf-8"))));
            return new String(cleanBytes, charset);
        } catch (Exception e) {
            log.info("AES解密异常，content:{}，charset:{}，异常信息：{}", content, charset, e.getMessage());
            throw new Exception("111111");
        }
    }
    /**
     * AES加密
     *
     * @param content
     * @param aesKey
     * @param charset
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content, String aesKey, String charset)
            throws Exception {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //AES/CBC/PKCS5Padding
            String str = "0000000000000000";
            IvParameterSpec iv = new IvParameterSpec(str.getBytes()); //0000000000000000.getBytes()
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey.getBytes(), "AES"), iv); //AES
            byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
            return new String(Base64.encodeBase64(encryptBytes));
        } catch (Exception e) {
            log.info("AES加密异常，content:{}，charset:{}，异常信息：{}", content, charset, e.getMessage());
            throw new Exception("111111");
        }
    }
}
